package serialport

import android_serialport_api.SerialPort
import ext.isChecked
import ext.toHexString
import java.io.File
import java.io.IOException

class Port(name: String) : SerialPort(File(name), 9600, 0) {
    private val out = outputStream
    private val input = inputStream
    private val header = ByteArray(2)

    fun write(byteArray: ByteArray) {
        out.write(byteArray)
    }

    fun read(byteArray: ByteArray): Int {
        return input.read(byteArray)
    }

    fun readPackage(): ByteArray {

        val head = input.read()
        if (head < 0) {
            throw IOException("串口接收 接收 串口关闭？")
        }
        if (head != 0xE1) {
            throw IllegalStateException("串口接收错误:head=$head")
        }

        val size = input.read()
        if (size < 0) {
            throw IOException("串口接收 接收 串口关闭？")
        }
        if (size < 5) {
            throw IllegalStateException("串口接收错误:size=$size")
        }

        val buf = ByteArray(size)
        buf[0] = head.toByte()
        buf[1] = size.toByte()

        var offset = 2

        while (offset < size) {
            val len = input.read(buf, offset, size - offset)
            if (len < 0) {
                throw IOException("串口接收 接收 串口关闭？")
            }
            offset += len
        }
        if (buf.isChecked()) {
            return buf
        }
        throw IllegalStateException("串口接收错误:${buf.toHexString()}")
    }

}
// e1 1c 94 00 00 00 00 00 00 00 00 03 03 07 79 4b 6e 3b 06 00 23 00 ef e1 06 7f 00 00
// e1 1c 94 00 00 00 00 00 00 00 00 03 03 07 79 4b 6e 3b 06 00 1f 00 00 02 09 00 72 ef